import json
import requests
import re

import notice


class Config:
    def __init__(self, sender, receivers, host, port, password):
        self.password = password
        self.sender = sender
        self.receivers = receivers
        self.host = host
        self.port = port


class Fund:
    def __init__(self,
                 code,
                 value,  # 基金成本
                 dec,  # 损失成本百分比
                 rise  # 盈利百分比

                 ):
        self.code = code
        self.value = value
        self.dec = dec
        self.rise = rise

    @property
    def dec_value(self):
        return self.value*(1.0 - self.dec)

    @property
    def rise_value(self):
        return self.value*(1.0 + self.rise)

    def if_notify(self, v):
        """
        当前基金跌幅和盈利超出预期
        """
        return self.dec_value <= v or self.rise_value >= v


def get_found_info_now(fund_code):
    """
    获取基金实时信息，天天基金数据接口：https://fundgz.1234567.com.cn/js/基金代码.js
    :param fund_code:
    :return: 基金实时信息 -->dict
    fundcode -- 基金代码
    name     -- 基金名称
    jzrqv    -- 上一个交易日
    dwjz     -- 基金净值（截止上一个交易日）
    gsz      -- 估计净值（实时）
    gszzl    -- 估计涨幅（实时）
    gztime   -- 更新时间（实时）
    """

    url = f'https://fundgz.1234567.com.cn/js/{fund_code}.js'
    response = requests.get(url=url)
    response.encoding = 'utf-8'
    pattern = r'^jsonpgz\((.*)\)'
    data = re.findall(pattern, response.text)[0]
    js_data = json.loads(data)
    return js_data


if __name__ == "__main__":

    with open('./config.json', 'r', encoding='utf8') as fp:
        json_data = json.load(fp)
        config = Config(sender=json_data['sender'],
                        receivers=json_data['receivers'],
                        host=json_data['host'],
                        port=json_data['port'],
                        password=json_data['password'])

    found_list = [
        Fund(code='320007', value=1.5146, dec=0.2, rise=0.2),
        Fund(code='012414', value=1.1466, dec=0.2, rise=0.2)

    ]

    for fd in found_list:
        res = get_found_info_now(fd.code)
        value_now = float(res.get('gsz'))
        name = res.get('name')
        gszzl = res.get('gszzl')
        print(res)
        if fd.if_notify(value_now):
            text = f'你关注的基金:{name}\n' \
                   f'当前预期涨跌幅:{gszzl}%\n' \
                   f'当前净值不符合您设定的预期，请及时登录软件查看\n'
            notice.notice(config=config, text=text)
